/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jjsoft.celularessuc.gco.ui;

import com.jjsoft.celularessuc.gco.mdl.DeudaProveedor;
import com.jjsoft.celularessuc.gco.mdl.Proveedor;
import com.jjsoft.celularessuc.gco.neg.DeudaProveedorManager;
import com.jjsoft.celularessuc.gco.neg.ProveedorManager;
import com.jjsoft.celularessuc.gco.util.CNumeros;
import com.jjsoft.celularessuc.gco.util.MiModelo;
import java.util.List;
import javax.swing.JOptionPane;

/**
 *
 * @author javila
 */
public class VSeleccionProveedorPagoDeuda extends javax.swing.JFrame {

    /**
     * Creates new form VSeleccionProveedorPagoDeuda
     */
    ProveedorManager pm = new ProveedorManager();
    List<Proveedor> proveedores;
    List<DeudaProveedor> deudas;
    DeudaProveedorManager dm = new DeudaProveedorManager();

    public VSeleccionProveedorPagoDeuda() {
        initComponents();
        cargarProveedores();
        cmdActualizaDeudas.setVisible(false);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cboProveedor = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtgDeuda = new javax.swing.JTable();
        cmdRegistrarPago = new javax.swing.JButton();
        cmdVerPagos = new javax.swing.JButton();
        cmdCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtDeudaTotal = new javax.swing.JTextField();
        cmdActualizaDeudas = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Pago de Deudas a Proveedores");

        jLabel3.setText("Proveedor:");

        cboProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboProveedorActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(0, 51, 255));
        jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel4.setText("Seleccione una Deuda");

        dtgDeuda.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setViewportView(dtgDeuda);

        cmdRegistrarPago.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/edit21.png"))); // NOI18N
        cmdRegistrarPago.setText("Registrar Pago");
        cmdRegistrarPago.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdRegistrarPagoActionPerformed(evt);
            }
        });

        cmdVerPagos.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/listar.png"))); // NOI18N
        cmdVerPagos.setText("Ver Pagos");
        cmdVerPagos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdVerPagosActionPerformed(evt);
            }
        });

        cmdCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.png"))); // NOI18N
        cmdCancelar.setText("Cancelar");
        cmdCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCancelarActionPerformed(evt);
            }
        });

        jLabel2.setText("Deuda total al Proveedor:");

        txtDeudaTotal.setEditable(false);

        cmdActualizaDeudas.setText("jButton1");
        cmdActualizaDeudas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdActualizaDeudasActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 682, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(cmdRegistrarPago)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmdVerPagos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cmdActualizaDeudas, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(43, 43, 43)
                        .addComponent(cmdCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cboProveedor, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDeudaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtDeudaTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmdRegistrarPago)
                    .addComponent(cmdVerPagos)
                    .addComponent(cmdCancelar)
                    .addComponent(cmdActualizaDeudas))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(718, 350));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_cmdCancelarActionPerformed

    private void cboProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboProveedorActionPerformed
        // TODO add your handling code here:
        if (evt.getModifiers() == 16) {
            if (cboProveedor.getSelectedIndex() > 0) {
                deudas = dm.listaDeudasPorProveedor(proveedores.get(cboProveedor.getSelectedIndex() - 1), 1);
                if (deudas != null && !deudas.isEmpty()) {
                    cargarDeudas();
                } else {
                    limpiarDeudas();
                }
            } else {
                limpiarDeudas();
            }

        }
    }//GEN-LAST:event_cboProveedorActionPerformed

    private void cmdRegistrarPagoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdRegistrarPagoActionPerformed
        // TODO add your handling code here:
        if (dtgDeuda.getSelectedRow() != -1) {
            new VRegistrarPagoDeudaProveedor(deudas.get(dtgDeuda.getSelectedRow()),cmdActualizaDeudas).show();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione una deuda para realizar el pago", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdRegistrarPagoActionPerformed

    private void cmdActualizaDeudasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdActualizaDeudasActionPerformed

        // TODO add your handling code here:
        if (cboProveedor.getSelectedIndex() > 0) {
                deudas = dm.listaDeudasPorProveedor(proveedores.get(cboProveedor.getSelectedIndex() - 1), 1);
                if (deudas != null && !deudas.isEmpty()) {
                    cargarDeudas();
                } else {
                    limpiarDeudas();
                }
            } else {
                limpiarDeudas();
            }
    }//GEN-LAST:event_cmdActualizaDeudasActionPerformed

    private void cmdVerPagosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdVerPagosActionPerformed
 // TODO add your handling code here:
        if (dtgDeuda.getSelectedRow() != -1) {
            new VVerPagosAProveedor(deudas.get(dtgDeuda.getSelectedRow())).show();
        } else {
            JOptionPane.showMessageDialog(rootPane, "Seleccione una deuda para ver el historia de pagos", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_cmdVerPagosActionPerformed
    private void cargarProveedores() {
        proveedores = pm.listarProveedores();
        cboProveedor.addItem("Seleccione un proveedor...");
        for (Proveedor proveedor : proveedores) {
            cboProveedor.addItem(proveedor.getNombre());
        }
    }

    private void cargarDeudas() {
        MiModelo modelo = new MiModelo();
        String[] identificadores = {"Id", "Concepto", "Fecha", "Monto", "Saldo", "F. Vencimiento"};
        modelo.setColumnIdentifiers(identificadores);

        double saldo = 0;
        for (DeudaProveedor deuda : deudas) {
            String fVencimiento = "";
            if (deuda.getFechaVencimiento() != null) {
                fVencimiento = deuda.getFechaVencimiento().toLocaleString().split(" ")[0];
            }
            String[] itemDeuda = {deuda.getIdDeuda().toString(), deuda.getConcepto(), deuda.getFecha().toLocaleString().split(" ")[0], CNumeros.Formato(deuda.getMontoInicial()), CNumeros.Formato(deuda.getSaldoActual()), fVencimiento};
            modelo.addRow(itemDeuda);
            saldo += deuda.getSaldoActual();
        }
        this.txtDeudaTotal.setText(CNumeros.Formato(saldo));
        this.dtgDeuda.setModel(modelo);
        this.dtgDeuda.getColumn("Id").setPreferredWidth(25);
        this.dtgDeuda.getColumn("Concepto").setPreferredWidth(200);
    }

    private void limpiarDeudas() {
        MiModelo modelo = new MiModelo();
        this.dtgDeuda.setModel(modelo);
        txtDeudaTotal.setText("");
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VSeleccionProveedorPagoDeuda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VSeleccionProveedorPagoDeuda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VSeleccionProveedorPagoDeuda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VSeleccionProveedorPagoDeuda.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VSeleccionProveedorPagoDeuda().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboProveedor;
    private javax.swing.JButton cmdActualizaDeudas;
    private javax.swing.JButton cmdCancelar;
    private javax.swing.JButton cmdRegistrarPago;
    private javax.swing.JButton cmdVerPagos;
    private javax.swing.JTable dtgDeuda;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField txtDeudaTotal;
    // End of variables declaration//GEN-END:variables
}
